package users

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"github.com/beego/beego/v2/server/web/pagination"
	"log"
	"strconv"
	"strings"
	"xpms/controllers"
	"xpms/cores"
	"xpms/cores/utils"
)

// 部门管理
type ManageDepartmentController struct {
	controllers.BaseController
}

// @Title 部门
// @Description 分页查询职位
// @Param	p		query 	int	true		"第几页"
// @Param	pageoffset		query 	int			"每页数"
// @Param	keywords		query 	string			"关键字搜索"
// @Param	status		query 	int			"状态"
// @Success 200 {object} users.Departs  int   int  int
// @Failure 403  not exist
// @router /page [get]
func (u *ManageDepartmentController) Page() {
	page, err := u.GetInt("p")
	if err != nil {
		page = 1
	}
	offset, err := u.GetInt("pageoffset")
	status := u.GetString("status")
	keywords := u.GetString("keywords")
	condArr := make(map[string]string)
	condArr["keywords"] = keywords
	condArr["status"] = status
	count := CountDeparts(condArr)
	paginator := pagination.SetPaginator(u.Ctx, offset, count)
	_, _, modeleData := ListDeparts(condArr, page, offset)
	type data struct {
		Departs  []Departs
		Total    int64
		PageNums int
		Page     int
	}
	d := &data{modeleData, paginator.Nums(), paginator.PageNums(), paginator.Page()}
	var responseEntity cores.ResponseEntity
	u.Data["json"] = responseEntity.Build(d).Data
	u.Ctx.Output.Status = responseEntity.StatusCode
	u.ServeJSON()
}

type DepartmentDTO struct {
	Name   string
	Desc   string
	Status int
}

// 如果你的 struct 实现了接口 validation.ValidFormer
// 当 StructTag 中的测试都成功时，将会执行 Valid 函数进行自定义验证
func (u *DepartmentDTO) Valid(v *validation.Validation) {
	v.Required(u.Name, "name").Message("部门名称不为空")
}

// @Title CreateDepartment
// @Description create Department
// @Param	body		body 	users.DepartmentDTO	true		"body for Department content"
// @Success 200 {int} users.Department.Id
// @Failure 403 body is empty
// @router / [post]
func (u *ManageDepartmentController) CreateDepartment() {
	var f PositionsDTO
	err := json.Unmarshal(u.Ctx.Input.RequestBody, &f)
	// 开始校验输入值
	valid := validation.Validation{}
	b, err := valid.Valid(&f)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	exists, err1 := GetDepartsByName(f.Name)
	if err1 != nil || !utils.IsEmpty(exists.Id) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "部门名称重复"}
		u.ServeJSON()
		return
	}
	var pos Departs
	pos.Id = utils.SnowFlakeId()
	pos.Name = f.Name
	pos.Desc = f.Desc
	err = AddDeparts(pos)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "添加成功", "id": fmt.Sprintf("%d", pos.Id)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "添加失败"}
	}
	u.ServeJSON()
}

// @Title UpdateDeparts
// @Description  UpdateDeparts
// @Param	id		path 	string	true		"Departs id"
// @Param	body		body 	users.DepartmentDTO	true		"body for Departs content"
// @Success 200 {string} 更新成功
// @Failure 403 body is empty
// @router /:id [put]
func (u *ManageDepartmentController) UpdateDeparts() {
	ids, err := u.GetInt64(":id")
	if err != nil || ids <= 0 {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "你选择更新的部门为空"}
		u.ServeJSON()
		return
	}
	var f PositionsDTO
	err = json.Unmarshal(u.Ctx.Input.RequestBody, &f)
	// 开始校验输入值
	valid := validation.Validation{}
	b, err := valid.Valid(&f)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	exist, err1 := GetDeparts(ids)
	if err1 != nil || utils.IsEmpty(exist.Name) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "部门不存在"}
		u.ServeJSON()
		return
	}
	existName, err1 := GetDepartsByName(f.Name)
	if err1 != nil || (!utils.IsEmpty(existName.Id) && existName.Id != exist.Id) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "职位重复"}
		u.ServeJSON()
		return
	}
	var pos Departs
	pos.Name = f.Name
	pos.Desc = f.Desc
	err = UpdateDeparts(ids, pos)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息修改成功", "id": fmt.Sprintf("%d", ids)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息修改失败"}
	}
	u.ServeJSON()

}

// @Title Update Departs status
// @Description  UpdateDeparts
// @Param	id		path 	string	true		"Departs id"
// @Param	status	query 	string	true		"Departs 状态"
// @Success 200 {string} 更新成功
// @Failure 403 body is empty
// @router /:id/status [put]
func (u *ManageDepartmentController) UpdateDepartsStatus() {
	ids, err := u.GetInt64(":id")
	if err != nil || ids <= 0 {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "你选择更新的部门为空"}
		u.ServeJSON()
		return
	}
	status, err := u.GetInt("status")
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "状态为空"}
		u.ServeJSON()
		return
	}
	exist, err1 := GetDeparts(ids)
	if err1 != nil || utils.IsEmpty(exist.Name) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "部门不存在"}
		u.ServeJSON()
		return
	}
	err = ChangeDepartStatus(ids, status)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息修改成功", "id": fmt.Sprintf("%d", ids)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息修改失败"}
	}
	u.ServeJSON()
}

// @Title Get
// @Description get Depart  by id
// @Param	id		path 	string	true		"The key for Depart"
// @Success 200 {object} users.Depart
// @Failure 403 :id is empty
// @router /:id [get]
func (u *ManageDepartmentController) Get() {
	uid := u.GetString(":id")
	if uid != "" {
		var responseEntity cores.ResponseEntity
		int64, err := strconv.ParseInt(uid, 10, 64)
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
			return
		}
		modelData, err := GetDeparts(int64)
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
		} else {
			u.Data["json"] = responseEntity.Build(modelData).Data
			u.Ctx.Output.Status = responseEntity.StatusCode
		}
	}
	u.ServeJSON()
}
